package com.xtaller.test.config.aop;

import com.alibaba.fastjson.JSONObject;
import lombok.var;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-08-22
 * @Description:
 */
@Aspect
@Component
public class HttpLogAop {
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    ThreadLocal<JSONObject> log = new ThreadLocal<>();

    @Pointcut("execution(public * com.xtaller.test.api..*.*(..))")
    public void httpLog(){}


    @Before("httpLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        String method = request.getMethod();
        String path = request.getServletPath();
        var params = request.getParameterMap();
        System.err.println("开始执行时间:" + startTime.get());
        var logStr = String.format("token: %s,method:%s,path:%s,param:%s",
                token, method, path, params);
        System.err.println(logStr);
    }

    @AfterReturning(returning = "ret", pointcut = "httpLog()")
    public void doAfterReturning(Object ret) {

        Long time = System.currentTimeMillis() - startTime.get();
        System.err.println("执行结束时间:" + System.currentTimeMillis());

        System.err.println("收集结果:" + ret.toString());
        // 1 创建一条数据   1
        // 2 修改一条数据   1

//        var methods = Arrays.asList("put", "delete", "post");
//        if(methods.contains(obj.getString(METHOD).toLowerCase())){
//            var item = JsonHelper.o2j(ret).getJSONObject("body");
//            var code = item.getInteger("code");
//            Long time = System.currentTimeMillis() - startTime.get();
//            if(code.equals(SUCCESS)) {
//                var url = obj.getString("url");
//                obj.put("time", time);
//                if(url.indexOf(COMMON) < 0) {
//                    logTask.setLog(obj, item);
//                }
//            }
//        }
    }

}
